# -*-coding:utf-8 -*-
import threading
import main.ble_scan
import main.bt_scan
import main.port_check
import main.ty_log
import main.probe
from bluepy.btle import Scanner
import prettytable as pt
from time import sleep
import bluetooth
import time
import hhtest
import eventlet
import json
from translate import Translator
import configparser
import os
from blueleakScan import blueleakscan
from bluetools import tools
# 全局变量 wifi 蓝牙 输出信打印到dic
dic = {}
info1 = {}
newClass = {}
translator = Translator(from_lang="chinese", to_lang="english")

__author__ = 'wuyou'

def writeinIni(maclist):
    cf = configparser.ConfigParser()
    filename = cf.read("attack.ini")
    cf.set("MAC", "mac", maclist)
    with open("attack.ini", "w+") as f:
        cf.write(f)

def getInfo1(addr,addrType):
    try:
        info1 = main.ble_scan.Ble(addr, addrType).getInfo()
        return info1
    except UnboundLocalError:
        pass
#  低功耗蓝牙
def bleScan():
    global dic
    inf4 = {}
    #while True:
    print '-----------------------低功耗蓝牙----------------------'
    scanner = Scanner().withDelegate(main.ble_scan.ScanDelegate())
    #devices list

    devices = scanner.scan()
    #
    tb = pt.PrettyTable()
    tb.field_names = ["MAC", "MAC类型", "信号强度", "Flags", "厂商", "服务(UUID)", "属性", "handle", "ch_type", "detail"]
    for dev in devices:

        print '**************************************************************************'
        print "Device %s (%s), RSSI=%d dB" % (dev.addr, dev.addrType, dev.rssi)
        print dev.getScanData()
        for (adtype, desc, value) in dev.getScanData():

            print "%s = %s" % (desc, value)
            if desc == 'Manufacturer':
                manufac = value
            if desc == 'Flags':
                flags = value
            if desc == 'Complete Local Name':
                devicename = value
        services = ''
        try:
            aa={}
            inf2 = {}
            inf3 = {}
            manu = ""
            '''
            if manufac[0:8] == '4c001005':
                continue
            elif manufac[0:8] == '004c0224':
                continue
            elif manufac[0:8] == '4c000c0e':
                continue
            elif manufac[0:8] == '4c000719':
                continue
            else:
            '''
               # eventlet.monkey_patch()
               # with eventlet.Timeout(60, False):
           # threadinfo = threading.Thread(target=getInfo1, args=(dev.addr, dev.addrType))
            #cancel_tmr = 1
            #threadinfo.start()
           # threadinfo.join(30)
           # if threadinfo.isAlive()==False:
            #  int = 0
           # if cancel_tmr == 1:
            #  threading.Timer(1, getInfo1, [dev.addr, dev.addrType]).start()
            #  time.sleep(30)
            #  cancel_tmr = int
            try:
                # {service1:{chara1:[handle, properties, readType, readMsg], chara2}}
               info =main.ble_scan.Ble(dev.addr, dev.addrType).getInfo()
               #print info
               #print type(info)
            except RuntimeError:
                continue
            for k, v in info.items():
                if v:
                    for ch, detail in v.items():
                        inf = {}
                        tb.add_row([dev.addr, dev.addrType, dev.rssi, dev.getScanData()[0][2], manufac,
                                    k.split('<')[1].split('>')[0], ch.split('<')[1].split('>')[0], detail[0],
                                    detail[1], detail])
                        #inf[dev.addr]= dev.addr
                        #inf['MACtype'] = dev.addrType
                        #inf['RSSI'] = dev.rssi
                        #inf['Flags'] = dev.getScanData()[0][2]
                        #manu = manufac
                        inf['Service(UUID)'] = k.split('<')[1].split('>')[0]
                        inf['character'] = ch.split('<')[1].split('>')[0]
                        #inf['handle'] = detail[0]
                        inf['ch_type'] = detail[1]
                        inf2[detail[0]] = inf
            print inf2
            inf3['MAC type'] = main.bt_scan.bt_device_type(translator.translate(devicename))
            inf3['RSSI'] = dev.rssi
            inf3['service'] = inf2
            inf3['MAC'] = dev.addr
            #inf3['Manufac'] = manufac
            inf3['Flags'] = flags
            inf3['devicename'] = translator.translate(devicename)
            inf3['status'] = 'on'

            main.probe.do_log_for_ble(inf3)
            #main.ty_log.info(json.dumps(inf3), send2syslog=True)
            inf4[dev.addr] = inf3
            #continue
            print tb
        except UnboundLocalError:
            pass
        except AttributeError:
            pass
        continue

    dic['BLE BLUETOOTH'] = inf4
    sleep(4)
   # sleep(1)
# 经典蓝牙
def bt():

    global dic
    global newClass
    maclistnow = []
    macforleak = []
    classdevice2 = {}
    print '-----------------经典蓝牙--------------------------------'
    nearby_devices = bluetooth.discover_devices(lookup_names=True, lookup_class=True)
    print nearby_devices
    print "scan end!"
    # MAC mesage for attack scan
    maclist = ""
    for addr,name,device_type in nearby_devices:
        maclistnow.append(addr)
        macforleak.append(addr)
        classdevice = {}

        try:
            # service scan and print
           svc = main.bt_scan.bt_device_service(str(addr), name, device_type)
        except:
            break
        # save results in dict
        classdevice['MAC'] = addr
        maclist = maclist+','+ addr
        #classdevice['deviceName'] = translator.translate(name)
        classdevice['deviceName'] = name
        classdevice['device_type'] = main.bt_scan.bt_device_type(device_type)
        status = 'on'
        classdevice['status'] = status
        if isinstance(svc, dict):
            classdevice['name'] = svc['name']
            classdevice['host'] = svc['host']
            classdevice['description'] = svc['description']
            classdevice['provider'] = svc['provider']
            classdevice['port'] = svc["port"]
            classdevice['protocol'] = svc["protocol"]
            classdevice['profiles'] = svc['profiles']
            classdevice['service-id'] = svc['service-id']
            classdevice['pro'] = svc['pro']
            classdevice2[addr] = classdevice
            #main.ty_log.info(json.dumps(main.probe.do_log_for_bt(classdevice)), send2syslog=True)
        else:
            classdevice['name'] = "unknown"
            classdevice['host'] = "unknown"
            classdevice['description'] = "unknown"
            classdevice['provider'] = "unknown"
            classdevice['port'] = "unknown"
            classdevice['protocol'] = "unknown"
            classdevice['profiles'] = "unknown"
            classdevice['service-id'] = "unknown"
            classdevice['pro'] = "unknown"
            classdevice2[addr] = classdevice
            #main.ty_log.info(json.dumps(main.probe.do_log_for_bt(classdevice)), send2syslog=True)
        main.probe.do_log_for_bt(classdevice)

        #main.ty_log.info(json.dumps(classdevice), send2syslog=True)
    if newClass:
        for k,v in newClass.items():
            if (k in maclistnow):
                continue
            else:
                #print k,v
                classdevice = {}
                try:
                    svc = main.bt_scan.bt_device_service(str(k), v['deviceName'], v['device_type'])
                except Exception:
                    print "ERRRRRRRRRRRRRRRRRRRRRRRR"
                    break
                classdevice['MAC'] = k
                maclist = maclist +','+ k
                macforleak.append(k)
                classdevice['deviceName'] = v['deviceName']
                classdevice['device_type'] = v['device_type']
                if isinstance(svc, dict):
                    status = 'on'
                    classdevice['name'] = svc['name']
                    classdevice['host'] = svc['host']
                    classdevice['description'] = svc['description']
                    classdevice['provider'] = svc['provider']
                    classdevice['port'] = svc["port"]
                    classdevice['protocol'] = svc["protocol"]
                    classdevice['profiles'] = svc['profiles']
                    classdevice['service-id'] = svc['service-id']
                    classdevice['pro'] = svc['pro']
                    classdevice['status'] = status
                    classdevice2[k] = classdevice
                    #main.ty_log.info(json.dumps(main.probe.do_log_for_bt(classdevice)), send2syslog=True)
                else:
                    status = 'off'
                    classdevice['name'] = "unknown"
                    classdevice['host'] = "unknown"
                    classdevice['description'] = "unknown"
                    classdevice['provider'] = "unknown"
                    classdevice['port'] = "unknown"
                    classdevice['protocol'] = "unknown"
                    classdevice['profiles'] = "unknown"
                    classdevice['service-id'] = "unknown"
                    classdevice['pro'] = "unknown"
                    classdevice['status'] = status
                    classdevice2[k] = classdevice
                    #main.ty_log.info(json.dumps(main.probe.do_log_for_bt(classdevice)), send2syslog=True)
                main.probe.do_log_for_bt(classdevice)
                #main.ty_log.info(json.dumps(classdevice), send2syslog=True)
    newClass = classdevice2
    writeinIni(maclist)
    sss = ['22:22:82:8e:ca:64']
    #blueleak = blueleakscan.leak(macforleak)
    #print 'maccccc===', blueleak
    #main.probe.do_log_for_blueleak(blueleak)
    print classdevice2
    dic['CLASSIC BLUETOOTH'] = classdevice2
    return classdevice2

def bluescan():
    while True:
        time.sleep(0.5)
        try:
            #bt()
            bleScan()
            print 'Print -----------dic----------------------------------'
            print dic
        # main.ty_log.info(dic)
        # main.ty_log.send_to_syslog(json.dumps(dic))
        except RuntimeError:
            continue

# 创建线程
threads = []
# 经典蓝牙
#bt = threading.Thread(target=bt)
#threads.append(bt)
# 低功耗蓝牙
blue = threading.Thread(target=bluescan)
threads.append(blue)
#wifileakWatch = threading.Thread(target=tools.getCVE3846)
#threads.append(wifileakWatch)
# 网关端口扫描
# portCheck = threading.Thread(target=portCheck)
# threads.append(portCheck)


if __name__ == '__main__':
    for t in threads:
      #  t.setDaemon(True)
        t.start()
        #t.join()

